有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在textView中将焦点放在新生成文本的顶部?

我有一个简单的应用程序。当你按下按钮时,你会听到新的笑话。如果上一个屏幕比屏幕大,可以向下滚动。如果您转到底部,然后转到下一个笑话,您将被转移到新生成笑话的底部,但我希望它转到顶部,并自动显示笑话的开头。我该怎么做? 我假设它将通过java代码完成

谢谢你抽出时间


共 (1) 个答案

  1. # 1 楼答案

    使用scrollTo(int x, int y)方法,我喜欢让ScrollView环绕我的TextView,但我认为同样的方法只适用于TextView。希望你能理解

    罗尔夫

    示例

    xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <ScrollView
            android:id="@+id/scroll"
            android:layout_width="fill_parent"
            android:layout_height="130dp" >
    
            <TextView
                android:id="@+id/text"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="long\n\n\n\n\n\n\n\n long\n\n\n\n\n\n\n very text here!" />
    
        </ScrollView>
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="joke" />
    
    </LinearLayout>
    

    java:

    package org.sample.example;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ScrollView;
    import android.widget.TextView;
    
    public class AutoscrollActivity extends Activity implements OnClickListener {
        /** Called when the activity is first created. */
    
        private Button new_joke;
        private TextView joke;
        private ScrollView scroll;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new_joke = (Button) this.findViewById(R.id.button);
            new_joke.setOnClickListener(this);
            joke = (TextView) this.findViewById(R.id.text);
            scroll = (ScrollView) this.findViewById(R.id.scroll);
        }
    
        @Override
        public void onClick(View v) {
            joke.setText("Long\n\n\n\n\n\n\n\n joke \n\n\n\n\n\n\n\nlong joke joke");
            scroll.scrollTo(0, 0);
        }
    }